#include <string>
#include <iostream>
#include <cv.h>
#include <highgui.h>

#include "Picture.h"
#include "HumanPicture.h"
#include "GrabcutFilter.h"
#include "BlenderFilter.h"
#include "FilterWindow.h"

using namespace std;

int main(int argc, char* argv[]) {
    /* Load faces picture */
    if(argc<=2 || argc>4){
	cout << "usage: Ex2 foreground background [bodyIndex]" << endl;
	return -1;
    }    
    string foregroundPath(argv[1]);
    string backgroundPath(argv[2]);   
    unsigned int bodyIndex = 0;
    if(argc==4){
      bodyIndex = atoi(argv[3]);
    }
    HumanPicture foregroundPicture(foregroundPath	,
        string("bin/casscades/haarcascade_frontalface_alt.xml"));
    if(!foregroundPicture.isInitialized()){
        cout << "Unable to load foreground image (check path and type)" << endl;
        return -1;
    }

    /* Load background picture*/
    Picture backgroundPicture(backgroundPath);
    if(!backgroundPicture.isInitialized()){
        cout << "Unable to load background image (check path and type)" << endl;
        return -1;
    }
    /* Generate faces ROIs*/
    HumanPicture::Bodies bodies(foregroundPicture.fetchBodies());
       
    /* Based on that selection, initiate a grabcut-user-interaction*/
    GrabcutFilter gc(foregroundPicture, bodies);
    
    
    {
        /* Window for grabcat */
        FilterWindow grabcut_win(gc, string("Grabcut"), FilterWindow::DRAW);
        grabcut_win.refresh();

        HumanPicture::Faces faces(foregroundPicture.fetchFaces());
        grabcut_win.highlight(faces);

        grabcut_win.loop();
        /* No need window no more */
    }

    /* Create a foreground from grabcut result; */

    vector< vector<cv::Mat> > bodiesMat = gc.exportROIs();
    cout << "Found ROIs: " << bodies.size() << " !" << endl;
    if(bodyIndex >= bodies.size()){
	cout << "Body index is too big for the given picture, max index is " << bodies.size()-1 << endl;
	return -2;
    }
      
    vector <cv::Mat> oneBodyMaskAndPict = bodiesMat[bodyIndex];

    /* Create a blender filter */
    BlenderFilter blender(backgroundPicture, oneBodyMaskAndPict);
    
    {
        /* Window for blender */
        FilterWindow blender_win(blender, string("Blender"), FilterWindow::LAST_CLICK);
        blender_win.refresh();

        blender_win.loop();
        /* no need window no more*/
    }

    
    return 0;
}
